import React, { useEffect, useRef, useState } from "react";
import { Modal, Form, Input, Radio, Select, Button, Row, Col, Table, InputRef } from "antd";
import CloseOutlined from "@ant-design/icons/lib/icons/CloseOutlined";

import { ProjectType, EnvironmentType, PostConfig, ConfigData, HistoryItem } from "../../types"; // 从上上层目录导入
import { postConfig, publishConfig, queryConfig, queryPreviewConfig, rollbackConfig, tryMsg, useEnvConfig, useGetEnvironments, useGetHistoryConfigs, useGetProjects } from "../../service";
import { ColumnProps, TableProps } from "antd/es/table";
import moment from "moment";
import { Model } from "sequelize";
const { confirm } = Modal;

const { TextArea } = Input;
const { Option } = Select;


interface HistoryViewProps {
    visible: boolean;
    projectId?: number;
    projectName?: string
    envId?: number;
    // configData?: ConfigData,

    onClose: () => void;
    onSubmit: (data: PostConfig) => void;
  }
  
  interface FormData {
      projectId: number
      environmentId: number,
      dependencyProjectIds:Array<number>,
      content: string,
  } 
  
 
const columns:TableProps<HistoryItem>['columns'] = [
{
    title: 'id',
    dataIndex: 'id',
    key: 'id',
},
{
    title: '发布时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    render: (text) => moment(new Date(text)).format("YYYY-MM-DD HH:mm:ss"),
},
{
    title: '备注',
    dataIndex: 'memo',
    key: 'memo',
},

];

const HistoryView: React.FC<HistoryViewProps> = ({ projectId,projectName,visible, onClose, onSubmit }) => {
  const [form] = Form.useForm<PostConfig>();
  const [envId,setEnvId] = useState<number>(0);
  const { environments, environmentsLoading,loadEnv } = useGetEnvironments({});
  let  { configs, configsLoading, loadConfigs } = useGetHistoryConfigs({
      projectId: projectId, environmentId: envId
  });
  let inRef = useRef<InputRef>();

  const [reason, setReason] = useState('');
  useEffect(()=>{
    console.log("envId",envId)
    if(envId){
        loadConfigs();
    }
  },[envId])
//  let {configs, configsLoading} = {configs:{items:[]},configsLoading:false}
//  const    { environments, environmentsLoading,loadEnv } = {environments:[],environmentsLoading:true,loadEnv:()=>{}}
  const dataSource = configs?.items??[];
  
  // 输入过滤逻辑
  const filterOption = (input: string, option: any) => {
    return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
  };
  let initForm = {} 

  const handleConfirm = () => {
    Modal.confirm({
      title: '请输入原因',
      content: (
        <Input
         ref={inRef}
          placeholder="请输入原因"
          onChange={(e) => setReason(e.target.value)}
        />
      ),
      onOk: () => {

        tryMsg(async()=>{
            rollbackConfig({projectId:projectId,environmentId:envId,content:form.getFieldValue("content"),memo:inRef?.current?.input.value})
        })
      },
      onCancel: () => {
        console.log('取消操作');
      },
    });
  };
  const doRollbackConfig = handleConfirm
 
   
  
  const handleCancel = () => {
    form.resetFields();
    onClose();
  };
  return (
    <Modal
      title={`查看${projectName}历史`}
      open={visible}
      key={projectId+envId}
      destroyOnClose={true}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={doRollbackConfig}>
          回滚到此版本
        </Button>, 
      ]}
      closeIcon={<CloseOutlined />}
      width="80%" // 增加对话框宽度
    >
    
      <Form form={form} layout="vertical" initialValues={initForm}>
        <Row gutter={16}>
          <Col span={8}>
              
              <Form.Item
                        name="environmentId"
                        label="环境列表"
                        rules={[{ required: true, message: "请选择环境" }]}
                      >
                        <Select
                          placeholder="请选择环境"
                          showSearch
                          disabled={environmentsLoading}
                          filterOption={filterOption}
                          onChange={(id)=>{ 
                            form.setFieldValue("content",'')

                            setEnvId(id)
                          }}
                          loading={environmentsLoading}
                           options={environments?.map((project) => ({
                              label: `${project.description}(${project.name})` ,
                            value: project.id,
                          }))}
                        />
                            
                      </Form.Item>
             
            <Table onRow={(record)=>{
                return {
                    onClick: (event) => {
                        console.log("env",record.content)
                        form.setFieldValue("content",record.content)
                    }, // 点击行
                }
            }} loading={configsLoading} dataSource={dataSource} columns={columns} />
          </Col>
          <Col span={16}>
            <Form.Item
              name="content"
              label="配置内容"
              rules={[{ required: true, message: "请输入配置内容" }]}
            >
              <TextArea rows={25} placeholder="请输入配置内容" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default HistoryView;